package org.jeecg.modules.demo.ch.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.Utils.OrderBomUtils;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChAssociationPrint;
import org.jeecg.modules.demo.ch.entity.ChAssociationPrintHistory;
import org.jeecg.modules.demo.ch.entity.ChParameter;
import org.jeecg.modules.demo.ch.exception.CustomException;
import org.jeecg.modules.demo.ch.service.IChAssociationPrintHistoryService;
import org.jeecg.modules.demo.ch.service.IChAssociationPrintService;
import org.jeecg.modules.demo.ch.service.IChParameterService;
import org.jeecg.modules.demo.ch.service.IImaaTService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 联想打印小票
 * @Author: jeecg-boot
 * @Date: 2022-10-19
 * @Version: V1.0 ChJabilOuterBoxPrint
 */
@Api(tags = "联想打印小票")
@RestController
@RequestMapping("/ch/chAssociationPrint")
@Slf4j
public class ChAssociationPrintController extends JeecgController<ChAssociationPrint, IChAssociationPrintService> {
    @Autowired
    private IChAssociationPrintService chAssociationPrintService;

    @Autowired
    private IImaaTService iImaaTService;

    @Autowired
    private IChParameterService iChParameterService;

    @Autowired
    private IChAssociationPrintHistoryService chAssociationPrintHistoryService;

    @Value("${jabil.export.zhusubu.file.path}")
    private String jabilExportZhuSuBuFilePath;

    @Value("${jabil.export.heyuanchanghong.file.path}")
    private String jabilExportHeYuanChangHongFilePath;


    public static final String arr[] = {"20-05201-01A", "54-19568-00A", "54-19553-00A-D",
            "54-19568-00A-D", "54-20067-00A-D", "54-20067-01A-D", "54-20068-00A-D", "54-20069-00A-D",
            "54-20070-00A-D", "54-20071-00A-D", "54-20071-01A-D", "54-20074-00A-D"};

    /**
     * 分页列表查询
     *
     * @param chAssociationPrint
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "联想打印小票-分页列表查询")
    @ApiOperation(value = "联想打印小票-分页列表查询", notes = "联想打印小票-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChAssociationPrint>> queryPageList(ChAssociationPrint chAssociationPrint,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        String itemNo = chAssociationPrint.getItemNo();
        //   int totalNum = iImaaTService.selectitemNoInfoTotal(itemNo);
        // 分页从T100读取数据
        List<Map<String, Object>> mapList = iImaaTService.selectitemNoInfo(itemNo, pageNo, pageSize);
        // 构建需要入本地库的数据
        //  ArrayList<ChAssociationPrint> chAssociationPrints = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mapList)) {
            for (Map<String, Object> stringObjectMap : mapList) {
                String imaal003 = String.valueOf(stringObjectMap.get("IMAAL003"));//料号
                String imaal004 = String.valueOf(stringObjectMap.get("IMAAL004"));//品名
                String imaaud008 = String.valueOf(stringObjectMap.get("IMAAUD008"));//色号

                LambdaQueryWrapper<ChAssociationPrint> chAssociationPrintLambdaQueryWrapper = new QueryWrapper<ChAssociationPrint>().lambda();
                chAssociationPrintLambdaQueryWrapper.like(StringUtils.hasLength(itemNo), ChAssociationPrint::getItemNo, itemNo);
                List<ChAssociationPrint> list = chAssociationPrintService.list(chAssociationPrintLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(list)) {//本地库不为空 不设置默认值
                    continue;
                }

                ChAssociationPrint chAssociationPrintEntity = new ChAssociationPrint();
                chAssociationPrintEntity.setItemNo(OrderBomUtils.setStringIfNotNull(imaal003));
                chAssociationPrintEntity.setProductName(OrderBomUtils.setStringIfNotNull(imaal004));
                chAssociationPrintEntity.setColorCode(OrderBomUtils.setStringIfNotNull(imaaud008));
                //设置默认值
                String manufactureDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
                chAssociationPrintEntity.setManufactureDate(manufactureDate);//生产日期
                chAssociationPrintEntity.setLotNo(manufactureDate + CommonMst.PRINT.D);//生产批号
                chAssociationPrintEntity.setPackingDate(manufactureDate);//包装日期

                List<String> itemNos = Arrays.asList(arr);//特殊料号  设置厂商为i15403

                //通用料号处理
                if (StringUtils.hasLength(imaal003) && imaal003.length() >= 12) {
                    String substring = imaal003.substring(3, 5);
                    if (substring.equals(CommonMst.PRINT.ITEM_NO_DESIGN17)
                            || substring.equals(CommonMst.PRINT.ITEM_NO_DESIGN18)
                            || substring.equals(CommonMst.PRINT.ITEM_NO_DESIGN19)) {
                        chAssociationPrintEntity.setAa1(CommonMst.PRINT.AA1);//厂商1
                    }else if (substring.equals(CommonMst.PRINT.ITEM_NO_DESIGN20)){
                        chAssociationPrintEntity.setAa1(CommonMst.PRINT.AA1BAK);//厂商2
                    }else {
                        chAssociationPrintEntity.setAa1(CommonMst.PRINT.AA1);//厂商1
                    }
                }

                //处理特殊料号
                for (String no : itemNos) {
                    if (imaal003.indexOf(no) != -1){ //没有找到返回-1   找到了
                        chAssociationPrintEntity.setAa1(CommonMst.PRINT.AA1BAK);//厂商2
                    }
                }

                chAssociationPrintEntity.setEdition(CommonMst.PRINT.ZERO);//版本
                chAssociationPrintEntity.setMoldCavityNo(CommonMst.PRINT.ZERO);//模穴号
//                chAssociationPrintEntity.setOuterBox(CommonMst.PRINT.B); //默认外箱
                chAssociationPrintEntity.setModelName("");//机种名
                chAssociationPrintEntity.setMaterialTexture("");//材质
                //       chAssociationPrints.add(chAssociationPrintEntity);
                //根据料号新增或修改
                LambdaUpdateWrapper<ChAssociationPrint> chAssociationPrintLambdaUpdateWrapper = new UpdateWrapper<ChAssociationPrint>().lambda();
                chAssociationPrintLambdaUpdateWrapper.eq(ChAssociationPrint::getItemNo, imaal003);
                chAssociationPrintLambdaUpdateWrapper.set(ChAssociationPrint::getItemNo, imaal003);
                chAssociationPrintLambdaUpdateWrapper.set(ChAssociationPrint::getProductName, imaal004);
                chAssociationPrintLambdaUpdateWrapper.set(ChAssociationPrint::getColorCode, imaaud008);
                chAssociationPrintLambdaUpdateWrapper.set(ChAssociationPrint::getAa1, chAssociationPrintEntity.getAa1());//设置厂商
                chAssociationPrintService.saveOrUpdate(chAssociationPrintEntity, chAssociationPrintLambdaUpdateWrapper);
            }
        }

        //开始分页查询
//        QueryWrapper<ChAssociationPrint> queryWrapper = QueryGenerator.initQueryWrapper(chAssociationPrint, req.getParameterMap());
        LambdaQueryWrapper<ChAssociationPrint> chAssociationPrintLambdaQueryWrapper = new QueryWrapper<ChAssociationPrint>().lambda();
        chAssociationPrintLambdaQueryWrapper.like(StringUtils.hasLength(itemNo), ChAssociationPrint::getItemNo, itemNo);
        chAssociationPrintLambdaQueryWrapper.orderByAsc(ChAssociationPrint::getItemNo);
        Page<ChAssociationPrint> page = new Page<>(pageNo, pageSize);
        IPage<ChAssociationPrint> pageList = chAssociationPrintService.page(page, chAssociationPrintLambdaQueryWrapper);
        List<ChAssociationPrint> records = pageList.getRecords();
        for (ChAssociationPrint record : records) {
            record.setColorCode(OrderBomUtils.setStringIfNotNull(record.getColorCode()));//颜色为null 置为""
        }
        //  pageList.setTotal(totalNum);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param chAssociationPrint
     * @return
     */
    @AutoLog(value = "联想打印小票-添加")
    @ApiOperation(value = "联想打印小票-添加", notes = "联想打印小票-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChAssociationPrint chAssociationPrint) {
        checkParameter(chAssociationPrint);

//        LambdaQueryWrapper<ChAssociationPrint> chAssociationPrintLambdaQueryWrapper = new QueryWrapper<ChAssociationPrint>().lambda();
//        chAssociationPrintLambdaQueryWrapper.eq(ChAssociationPrint::getItemNo,chAssociationPrint.getItemNo());
//        List<ChAssociationPrint> list = chAssociationPrintService.list(chAssociationPrintLambdaQueryWrapper);
//        if (!CollectionUtils.isEmpty(list)){
//            return Result.error("该料号已存在!");
//        }
        chAssociationPrintService.save(chAssociationPrint);
        return Result.OK("添加成功！");
    }

    /**
     * 生成箱号规则
     *
     * @param chAssociationPrint
     * @return ReelID （条码总长18位）
     * 箱号 （是B还是I 怎么取值 )
     * Bar Code  内容结构: 類別(B for 外箱,I for 內箱(1位))+Vendor code(6位)
     * + Part code（光寶料號的中間5位) +  Y(年,1位) + M(1-9 代表1-9月;A代表10月;
     * B代表11月;C代表12月(1位)) +4位流水号(按当月份从0001至FFFF 进行编制（16进制),
     * 每月从0001开始编排,Part code 相同时流水号统一编排)
     * B I34095
     * 15285 6 7 0001
     * <p>
     * BI3409515285670001
     */
    public String generateCaseNo(ChAssociationPrint chAssociationPrint) {
        //开始生成箱号规则
        StringBuffer stringBuffer = new StringBuffer("");
        String outerBox = chAssociationPrint.getOuterBox();
        String aa1 = chAssociationPrint.getAa1();
        String itemNo = chAssociationPrint.getItemNo().substring(3, 8);

        String manufactureDate = chAssociationPrint.getManufactureDate();
        String year = manufactureDate.substring(1, 2);
        String month = Integer.toHexString(Integer.parseInt(manufactureDate.substring(2, 4))).toUpperCase();

        String major_categories = "";//大类
        String little_class = "";//小类
        major_categories = CommonMst.PRINT.PRINT_LOCATION1;
        little_class = CommonMst.PRINT.SERIAL_NUMBER;

//        String printLocation = chAssociationPrint.getPrintLocation();
//        if (printLocation.equals(CommonMst.PRINT.HE_YUAN_CHANG_HONG)) {
//            major_categories = CommonMst.PRINT.PRINT_LOCATION2;
//            little_class = CommonMst.PRINT.SERIAL_NUMBER;
//        } else if (printLocation.equals(CommonMst.PRINT.CHANG_HONG_ZHU_SU_BU)) {
//            major_categories = CommonMst.PRINT.PRINT_LOCATION1;
//            little_class = CommonMst.PRINT.SERIAL_NUMBER;
//        }

        //生成流程号
        LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapper = new QueryWrapper<ChParameter>().lambda();
        chParameterLambdaQueryWrapper.eq(ChParameter::getMajorCategories, major_categories);
        chParameterLambdaQueryWrapper.eq(ChParameter::getLittleClass, little_class);
        List<ChParameter> list = iChParameterService.list(chParameterLambdaQueryWrapper);
        String num = leftZeroPadding(4, Integer.toHexString(Integer.parseInt(list.get(0).getValueStr())).toUpperCase());
        chAssociationPrint.setSerialNumber(num);
        String reelID = stringBuffer.append(outerBox).append(aa1).append(itemNo).append(year).append(month).append(num).toString();
        return reelID;
    }


    /**
     * 二维码
     * P   +  54-15285-00A;  料号
     * D   +  160524;        生产日期
     * L   +  160524D;       生产批号
     * V   +  I34095;        AA1  (VendorCode 光寶分配給廠商的代碼,長度為6位)  Y
     * Q   +  250;           外箱数量 (Quantity最小包装的数量;外箱 Label 时代表整箱的数量)
     * C   +  A;             模穴号(生產時的模穴號(沒有則放”0”))
     * R   +  3079803-003;   版本 (Revision生產時的版本號(此號碼將同時用于EC/Tracking card材料的標記))
     * S   +  BI3409515285670001  流水号 (Reel ID)  箱号 （是B还是I 怎么取值 )
     * <p>
     * P54-15285-00A;D160524;L160524D;VI34095;Q250;CA;R3079803-003;SBI3409515285670001
     * <p>
     * 2D條碼的規則:
     * 條碼信息的順序依次為①②③④⑤⑥⑦⑧每個信息開頭以對應的字母開頭,以”;”結束
     * 1D條碼的規則:
     * 條碼 =前綴碼+對應的內容,例如 PartNO 54-15285-00A,則對應的條碼內容為:  P54-15285-00A
     */
    public String generateQrCode(ChAssociationPrint chAssociationPrint) {
        //生成箱号以及二维码需要做的校验
        checkParameter(chAssociationPrint);
        StringBuffer stringBuffer = new StringBuffer();
        String itemNo = chAssociationPrint.getItemNo();
        String manufactureDate = chAssociationPrint.getManufactureDate();
        String lotNo = chAssociationPrint.getLotNo();
        String aa1 = chAssociationPrint.getAa1();
        String outerBoxesNum = chAssociationPrint.getOuterBoxesNum();
        String moldCavityNo = chAssociationPrint.getMoldCavityNo();
        if (!StringUtils.hasLength(moldCavityNo)) {
            moldCavityNo = "0";
        }
        String edition = chAssociationPrint.getEdition();
        String reelID = chAssociationPrint.getReelId();

        String casesNum = chAssociationPrint.getCasesNum();
        if (!StringUtils.hasLength(casesNum)) {
            chAssociationPrint.setCasesNum("1");
        }
        String mantissaQuantity = chAssociationPrint.getMantissaQuantity();
        if (!StringUtils.hasLength(mantissaQuantity)) {
            chAssociationPrint.setMantissaQuantity("0");
        }

        String qrCode = stringBuffer.append("P").append(itemNo).append(";")
                .append("D").append(manufactureDate).append(";")
                .append("L").append(lotNo).append(";")
                .append("V").append(aa1).append(";")
                .append("Q").append(outerBoxesNum).append(";")
                .append("C").append(moldCavityNo).append(";")
                .append("R").append(edition).append(";")
                .append("S").append(reelID).toString();
//        String qrCode = stringBuffer.append("P").append(itemNo)
//                .append("D").append(manufactureDate)
//                .append("L").append(lotNo)
//                .append("V").append(aa1)
//                .append("Q").append(outerBoxesNum)
//                .append("C").append(moldCavityNo)
//                .append("R").append(edition)
//                .append("S").append(reelID).toString();
        return qrCode;
    }


    /**
     * 向左补零
     *
     * @param num 要补的位数
     * @param str 数值
     * @return
     */
    public static String leftZeroPadding(int num, String str) {
        if (!StringUtils.hasLength(str) || str.length() == 0) {
            throw new RuntimeException("传入的需要补零的字符有误");
        }
        while (str.length() != num) {
            str = "0" + str;
        }
        return str;
    }

    /**
     * 编辑
     *
     * @param chAssociationPrint
     * @return
     */
    @AutoLog(value = "联想打印小票-编辑")
    @ApiOperation(value = "联想打印小票-编辑", notes = "联想打印小票-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChAssociationPrint chAssociationPrint) {
        log.info("传过来的参数chAssociationPrint:{}", chAssociationPrint);
        chAssociationPrintService.updateById(chAssociationPrint);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "联想打印小票-通过id删除")
    @ApiOperation(value = "联想打印小票-通过id删除", notes = "联想打印小票-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        chAssociationPrintService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "联想打印小票-批量删除")
    @ApiOperation(value = "联想打印小票-批量删除", notes = "联想打印小票-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.chAssociationPrintService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "联想打印小票-通过id查询")
    @ApiOperation(value = "联想打印小票-通过id查询", notes = "联想打印小票-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChAssociationPrint> queryById(@RequestParam(name = "id", required = true) String id) {
        ChAssociationPrint chAssociationPrint = chAssociationPrintService.getById(id);
        if (chAssociationPrint == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chAssociationPrint);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param chAssociationPrint
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChAssociationPrint chAssociationPrint) {
        return super.exportXls(request, chAssociationPrint, ChAssociationPrint.class, "联想打印小票");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param printLocation
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_association_print:exportXls")
    @RequestMapping(value = "/exportXls2")
    public void exportXls(HttpServletRequest request, String printLocation) {
        try {
            log.info("开始注塑部联想的excel导出 printLocation:{}", printLocation);
            if (!StringUtils.hasLength(printLocation)) {
                throw new CustomException("导出时,请选择打印地点!");
            }
            LambdaQueryWrapper<ChAssociationPrint> chAssociationPrintLambdaQueryWrapper = new QueryWrapper<ChAssociationPrint>().lambda();
            String selections = request.getParameter("selections");
            //过滤选中的数据
            if (!oConvertUtils.isNotEmpty(selections)) {
                throw new CustomException("请选择要导出的一条数据!");
            }
            //过滤选中的数据
            List<String> selectionList = Arrays.asList(selections.split(","));
            if (selectionList.size() > 1) {
                throw new CustomException("请选择要导出的一条数据!不可以多条!");
            }

            chAssociationPrintLambdaQueryWrapper.in(ChAssociationPrint::getId, selectionList);
            // Step.2 获取导出数据
            List<ChAssociationPrint> chAssociationPrints = chAssociationPrintService.list(chAssociationPrintLambdaQueryWrapper);
            ChAssociationPrint chAssociationPrint = chAssociationPrints.get(0);

            //计算需要导出的张数
            Integer totalNum = Integer.parseInt(chAssociationPrint.getTotalNum());//总数
            Integer outerBoxesNum = Integer.parseInt(chAssociationPrint.getOuterBoxesNum());

            int c = (int) Math.ceil((double) totalNum / outerBoxesNum);//张数
            //计算余数
            int remainder = totalNum - (c - 1) * outerBoxesNum;
            if (remainder != 0) {
                log.info("要导出的总数{},张数c{},前{}张数量是{},最后一张数量是{}", totalNum, c, c - 1, outerBoxesNum, remainder);
            } else {
                log.info("要导出的总数{}，张数c{},每张数量是{}", totalNum, c, outerBoxesNum);
            }

            // 定义导出的文件名
            String fileName = "";

            //重新构建要导出的集合
            List<ChAssociationPrint> chAssociationPrintList = new ArrayList<>();
            for (int i = 0; i < c; i++) { //遍历
                ChAssociationPrint chAssociationPrintEntity = new ChAssociationPrint();
                BeanUtils.copyProperties(chAssociationPrint, chAssociationPrintEntity);
                if (remainder != 0 && i == c - 1) {//余数不为0 并且 是最后一次循环时  让外箱数量等于计算的余数
                    chAssociationPrintEntity.setOuterBoxesNum(OrderBomUtils.setStringIfNotNull(remainder));
                }
                chAssociationPrintEntity.setPrintLocation(printLocation);
                //开始根据一些基础参数生成对应的规则重新赋值到实体中.
                //生成箱号规则
                String reelID = generateCaseNo(chAssociationPrintEntity);
                log.info("生成的箱号reelID:{}", reelID);
                if (reelID.length() != 18) {
                    throw new RuntimeException("生成的箱号有误!长度不是18位，请检查!");
                }
                chAssociationPrintEntity.setReelId(reelID);
                //生成二维码
                String qrCode = generateQrCode(chAssociationPrintEntity);
                chAssociationPrintEntity.setQrCode(qrCode);
                chAssociationPrintEntity.setAa2(chAssociationPrintEntity.getReelId().substring(0, 12));
                chAssociationPrintList.add(chAssociationPrintEntity);
                //更新流水号  +1
                String major_categories = "";//大类
                String little_class = "";//小类
                major_categories = CommonMst.PRINT.PRINT_LOCATION1;
                little_class = CommonMst.PRINT.SERIAL_NUMBER;
                if (printLocation.equals(CommonMst.PRINT.HE_YUAN_CHANG_HONG)) {
                    fileName = jabilExportHeYuanChangHongFilePath;
//                    major_categories = CommonMst.PRINT.PRINT_LOCATION2;
//                    little_class = CommonMst.PRINT.SERIAL_NUMBER;
                } else if (printLocation.equals(CommonMst.PRINT.CHANG_HONG_ZHU_SU_BU)) {
                    fileName = jabilExportZhuSuBuFilePath;
//                    major_categories = CommonMst.PRINT.PRINT_LOCATION1;
//                    little_class = CommonMst.PRINT.SERIAL_NUMBER;
                }
                //更新流水号  +1
                updateChParameter(major_categories, little_class);
            }

            log.info("文件输出的路径fileName:{},chAssociationPrintList.size():{}", fileName, chAssociationPrintList.size());
            //先删除文件及目录
            FileUtil.del(fileName);
            //创建文件，如果父目录不存在也自动创建
            makeDirectory(fileName);
            // 通过工具类创建writer
            ExcelWriter writer = ExcelUtil.getWriter(fileName);

            //自定义标题别名
            writer.addHeaderAlias("itemNo", "料号");
            writer.addHeaderAlias("manufactureDate", "生产日期");
            writer.addHeaderAlias("lotNo", "生产批号");
            writer.addHeaderAlias("edition", "版本");
            writer.addHeaderAlias("outerBoxesNum", "外箱数量");
            writer.addHeaderAlias("moldCavityNo", "模穴号");
            writer.addHeaderAlias("modelName", "机种名");
            writer.addHeaderAlias("productName", "品名");
            writer.addHeaderAlias("packingDate", "包装日期");
            writer.addHeaderAlias("materialTexture", "材质");
            writer.addHeaderAlias("colorCode", "色号");
            writer.addHeaderAlias("outerBox", "是否外箱（B外箱I内箱）");
            writer.addHeaderAlias("reelID", "箱号");
            writer.addHeaderAlias("qrCode", "二维码");
            writer.addHeaderAlias("AA1", "AA1");
            writer.addHeaderAlias("AA2", "AA2");
            writer.addHeaderAlias("serialNumber", "流水号");
            writer.addHeaderAlias("casesNum", "箱数");
            writer.addHeaderAlias("mantissaQuantity", "尾数数量");

            // 定义单元格背景色
            //StyleSet style = writer.getStyleSet();
            // 第二个参数表示是否也设置头部单元格背景
            // style.setBackgroundColor(IndexedColors.RED, false);

            // 合并单元格后的标题行，使用默认标题样式
            //   writer.merge(12, name);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(chAssociationPrintList, true);
            // 关闭writer，释放内存
            writer.close();

            //保存导出的记录
            saveChAssociationPrintHistory(chAssociationPrintList);

        } catch (Exception e) {
            log.error("注塑部联想的excel导出异常", e);
            throw new RuntimeException("注塑部联想的excel导出异常", e);
        }
    }

    /**
     * 保存导出的记录
     *
     * @param chAssociationPrints
     */
    public void saveChAssociationPrintHistory(List<ChAssociationPrint> chAssociationPrints) {
        ArrayList<ChAssociationPrintHistory> chAssociationPrintHistoryArrayList = new ArrayList<>();
        if (CollectionUtils.isEmpty(chAssociationPrints)) {
            return;
        }
        for (ChAssociationPrint chAssociationPrint : chAssociationPrints) {
            ChAssociationPrintHistory chAssociationPrintHistory = new ChAssociationPrintHistory();
            BeanUtils.copyProperties(chAssociationPrint, chAssociationPrintHistory);
            chAssociationPrintHistory.setId("");
            chAssociationPrintHistoryArrayList.add(chAssociationPrintHistory);
        }
        chAssociationPrintHistoryService.saveBatch(chAssociationPrintHistoryArrayList);
    }

    /**
     * 更新流水号  +1
     *
     * @param major_categories
     * @param little_class
     */
    public void updateChParameter(String major_categories, String little_class) {
        LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapper = new QueryWrapper<ChParameter>().lambda();
        chParameterLambdaQueryWrapper.eq(ChParameter::getMajorCategories, major_categories);
        chParameterLambdaQueryWrapper.eq(ChParameter::getLittleClass, little_class);
        List<ChParameter> list = iChParameterService.list(chParameterLambdaQueryWrapper);
        int numValue = Integer.parseInt(list.get(0).getValueStr());
        LambdaUpdateWrapper<ChParameter> chParameterLambdaUpdateWrapper = new LambdaUpdateWrapper<ChParameter>();
        chParameterLambdaUpdateWrapper.eq(ChParameter::getMajorCategories, major_categories);
        chParameterLambdaUpdateWrapper.eq(ChParameter::getLittleClass, little_class);
        chParameterLambdaUpdateWrapper.set(ChParameter::getValueStr, numValue + 1);
        iChParameterService.update(chParameterLambdaUpdateWrapper);
    }

    /**
     * 创建指定的目录。
     * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
     * <b>注意：可能会在返回false的时候创建部分父目录。</b>
     *
     * @param file 要创建的目录
     * @return 完全创建成功时返回true，否则返回false。
     * @since 1.0
     */
    public static boolean makeDirectory(File file) {
        File parent = file.getParentFile();
        if (parent != null) {
            return parent.mkdirs();
        }
        return false;
    }


    /**
     * 创建指定的目录。
     * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
     * <b>注意：可能会在返回false的时候创建部分父目录。</b>
     *
     * @param fileName 要创建的目录的目录名
     * @return 完全创建成功时返回true，否则返回false。
     * @since 1.0
     */

    public static boolean makeDirectory(String fileName) {
        File file = new File(fileName);
        return makeDirectory(file);
    }

    /**
     * 生成箱号以及二维码需要做的校验
     *
     * @param returnAssociationPrint
     */
    public static void checkParameter(ChAssociationPrint returnAssociationPrint) {
        //1.校验
        String itemNo = returnAssociationPrint.getItemNo();//料号
        String errMsgBegin = "原始文件Excel料号： ";
        String errMsgEnd = "";

        //校验料号是否为空
        if (!StringUtils.hasLength(itemNo)) {
            errMsgEnd = "料号不能为空! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        //校验总数
        if (null == returnAssociationPrint.getTotalNum()) {
            errMsgEnd = "总数不能为空! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }

        //校验打印地点
        if (!StringUtils.hasLength(returnAssociationPrint.getPrintLocation())) {
            errMsgEnd = "打印地点不能为空! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }

        //校验是否外箱（B外箱I内箱）
        if (!StringUtils.hasLength(returnAssociationPrint.getOuterBox())) {
            errMsgEnd = "是否外箱（B外箱I内箱）不能为空! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!(returnAssociationPrint.getOuterBox().equals("B") || returnAssociationPrint.getOuterBox().equals("I"))) {
            errMsgEnd = "原始文件维护的是否外箱（B外箱I内箱）必须是B或者I!\r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!StringUtils.hasLength(returnAssociationPrint.getAa1())) {
            errMsgEnd = "AA1  (VendorCode 光宝分配给供应商的代码)不能为空!\r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (returnAssociationPrint.getAa1().length() != 6) {
            errMsgEnd = "AA1  (VendorCode 光宝分配给供应商的代码)必须为6位!\r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!StringUtils.hasLength(returnAssociationPrint.getManufactureDate())) {
            errMsgEnd = "生产日期不能为空! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (returnAssociationPrint.getManufactureDate().length() != 6) {
            errMsgEnd = "生产日期必须为6位 示例：160524! \r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!StringUtils.hasLength(returnAssociationPrint.getLotNo())) {
            errMsgEnd = "LotNo生成批号，不能为空!长度建议不超过8位 示例:160524D\r\n";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!StringUtils.hasLength(returnAssociationPrint.getOuterBoxesNum())) {
            errMsgEnd = "外箱数量不能为空!";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
        if (!StringUtils.hasLength(returnAssociationPrint.getEdition())) {
            errMsgEnd = "版本不能为空!";
            throw new RuntimeException(errMsgBegin + itemNo + errMsgEnd);
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("ch_association_print:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChAssociationPrint.class);
    }

    public static void main(String[] args) {
        List<String> strings = Arrays.asList(arr);
        System.out.println("strings = " + strings);
        List<String> itemNos = Arrays.asList(arr);
        System.out.println("itemNos = " + itemNos);
    }

}
